package com.cqhz.quwan.ui.activity

import android.app.Activity
import android.app.AlertDialog
import android.content.DialogInterface
import android.content.Intent
import android.graphics.Color
import com.cqhz.quwan.APP
import com.cqhz.quwan.ActivityInject
import com.cqhz.quwan.R
import com.cqhz.quwan.common.KeyContract
import com.cqhz.quwan.model.*
import com.cqhz.quwan.mvp.buy.GoPaymentContract
import com.cqhz.quwan.mvp.buy.GoPaymentPresenter
import com.cqhz.quwan.ui.base.GoBackActivity
import com.cqhz.quwan.ui.login.LoginActivity
import com.cqhz.quwan.ui.main.order.OrderListActivity
import com.cqhz.quwan.ui.widget.dialog.PrizeDialog
import com.cqhz.quwan.ui.widget.dialog.RewardDialog
import com.cqhz.quwan.util.formatMoney
import com.cqhz.quwan.util.getInt
import kotlinx.android.synthetic.main.activity_go_payment.*
import me.militch.quickcore.core.HasDaggerInject
import me.militch.quickcore.util.ApiException
import javax.inject.Inject


/**
 * 去支付
 * Created by Guojing on 2018/9/26.
 */
class GoPaymentActivity : GoBackActivity(), GoPaymentContract.View, HasDaggerInject<ActivityInject> {

    @Inject
    lateinit var goPaymentPresenter: GoPaymentPresenter
    private var orderId: String? = null
    private var loginBean: LoginBean? = null
    private var userInfoBean: UserInfoBean? = null
    private var couponBean: CouponBean? = null
    private var orderAmount: Int = 0// 订单金额
    private var balance: Int = 0// 趣豆余额
    private var couponList = ArrayList<CouponBean>()
    private var isUseCoupon: Boolean = true// 是否使用优惠券

    companion object {
        const val REQUEST_SELECT_COUPON = 0x1001
    }

    override fun layout(): Int {
        return R.layout.activity_go_payment
    }

    override fun titleBarText(): String? {
        return "支付"
    }

    override fun inject(activityInject: ActivityInject) {
        activityInject.inject(this)
    }

    override fun initView() {
        goPaymentPresenter.attachView(this)
        initData()
        setOnClick()
    }

    private fun initData() {
        orderId = intent.getStringExtra(KeyContract.OrderId)
        orderAmount = intent.getDoubleExtra(KeyContract.Amount, 0.0).getInt()
        val actualAmount = intent.getDoubleExtra(KeyContract.ActualAmount, 0.0).getInt()
        val lotteryName = intent.getStringExtra(KeyContract.LotteryName)

        tv_lottery_info.text = lotteryName// 玩法
        tv_payment_amount.text = actualAmount.toString()// 订单金额
    }

    /**
     * 设置点击事件
     */
    private fun setOnClick() {
        action_goto_coupon.setOnClickListener { gotoSelectCouponActivity() }
        action_pay.setOnClickListener {
            if (userInfoBean != null) {
                if (balance < orderAmount) {
                    createDialog(title = "温馨提示",
                            msg = "当前账户趣豆余额不足，是否充值",
                            pos = "去充值", neg = "取消",
                            ok = { _, _ -> startActivity(Intent(context(), RechargeActivity::class.java)) },
                            no = { _, _ -> }).show()
                    return@setOnClickListener
                }

                if (isUseCoupon && couponList.size > 0 && couponBean == null) {
                    createDialog(title = "温馨提示",
                            msg = "您有红包待使用",
                            pos = "确定", neg = "取消",
                            ok = { _, _ -> gotoSelectCouponActivity() },
                            no = { _, _ ->
                                isUseCoupon = false
                                tv_coupon.text = "不使用优惠"
                                tv_coupon.setTextColor(Color.parseColor("#999999"))
                            }).show()
                    return@setOnClickListener
                }

                action_pay.isEnabled = false
                goPaymentPresenter.orderPay(loginBean!!.userId!!, orderId!!, if (couponBean != null) couponBean!!.couponId else null)// 趣豆支付
            } else {
                showToast("数据获取异常")
                return@setOnClickListener
            }
        }
    }

    /**
     * 跳转到选择优惠券
     */
    private fun gotoSelectCouponActivity() {
        if (couponList.size == 0) {
            return
        }
        val intent = Intent(this, SelectCouponActivity::class.java)
        intent.putExtra(KeyContract.OrderId, orderId)
        if (couponBean != null) {
            intent.putExtra(KeyContract.Bean, couponBean)
        }
        intent.putExtra(KeyContract.Selected, isUseCoupon)
        intent.putParcelableArrayListExtra(KeyContract.List, couponList)
        startActivityForResult(intent, REQUEST_SELECT_COUPON)
        overridePendingTransition(R.anim.fade_in, R.anim.fade_out)
    }

    override fun loadAvailableCouponList(list: List<CouponBean>) {
        couponList.clear()
        couponList.addAll(list)

        if (isUseCoupon && couponBean != null) {
            tv_coupon.text = "-" + couponBean!!.money
            tv_coupon.setTextColor(Color.parseColor("#d60000"))
        } else {
            if (!isUseCoupon) {
                tv_coupon.text = "不使用优惠"
                tv_coupon.setTextColor(Color.parseColor("#999999"))
            } else {
                tv_coupon.text = if (couponList.size > 0) couponList.size.toString() + "个可用" else "无可用"
                tv_coupon.setTextColor(Color.parseColor(if (couponList.size > 0) "#d60000" else "#999999"))
            }
        }
    }

    override fun setWindowList(list: List<WindowBean>) {
        // type 类型 1-中奖；2-邀请首单；3-邀请首冲；4-每日首单；5-新用户注册
        for (i in list.size - 1 downTo 0) {
            when (list[i].type) {
                "1" -> {
                    PrizeDialog(this)
                            .builder()
                            .setMsg(list[i].title)
                            .setBean(list[i].content)
                            .setActionConfirm("查看中奖订单") { startActivity(Intent(this, if (loginBean == null) LoginActivity::class.java else OrderListActivity::class.java)) }
                            .show()
                }
                "6" -> {
                    PrizeDialog(this)
                            .builder()
                            .setMsg(list[i].title)
                            .setBean(list[i].content)
                            .setActionConfirm("查看中奖订单") { startActivity(Intent(this, if (loginBean == null) LoginActivity::class.java else MyPredictionActivity::class.java)) }
                            .show()
                }
                else -> {
                    RewardDialog(this)
                            .builder()
                            .setMsg(list[i].title)
                            .setBean(list[i].content)
                            .setActionConfirm("确定")
                            .show()
                }
            }
        }
    }

    override fun showRequestError(e: ApiException) {
        super.showRequestError(e)
        action_pay.isEnabled = true
    }

    /**
     *
     * 创建弹出框
     */
    private fun createDialog(title: String = "", msg: String = "", pos: String = "", neg: String = "", ok: (DialogInterface, Int) -> Unit, no: (DialogInterface, Int) -> Unit): AlertDialog {
        return AlertDialog.Builder(this)
                .setTitle(title).setMessage(msg)
                .setPositiveButton(pos, ok)
                .setNegativeButton(neg, no).create()
    }

    override fun showUserInfo(userInfoBean: UserInfoBean) {
        this.userInfoBean = userInfoBean
        onDataChanged()
    }

    private fun onDataChanged() {
        this.balance = userInfoBean!!.balance.formatMoney().getInt()
        // 需付趣豆=订单趣豆-优惠券
        var orderPay = orderAmount
        if (couponBean != null) {
            orderPay -= couponBean!!.money
        }
        var useBean = if (orderPay > balance) balance else orderPay
        var lackLotBean = if (orderPay > balance) orderPay - balance else 0

        tv_balance_offset.text = useBean.toString()// 余额冲抵
        tv_payment_lack.text = lackLotBean.toString()// 还需支付
        action_pay.text = if (lackLotBean > 0) "充值" else "确认"
    }

    override fun showOrderInfo(orderInfo: OrderResp) {
        showToast("支付成功")
        val intent = Intent(context(), OrderDetailActivity::class.java)
        intent.putExtra(KeyContract.OrderId, orderInfo.id)
        intent.putParcelableArrayListExtra(KeyContract.List, couponList)
        startActivity(intent)
        finish()
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == Activity.RESULT_OK && requestCode == REQUEST_SELECT_COUPON && loginBean != null && data != null) {
            couponBean = data.getParcelableExtra<CouponBean>(KeyContract.Bean)
            isUseCoupon = data.getBooleanExtra(KeyContract.Selected, true)
        }
    }

    override fun onResume() {
        super.onResume()
        if (APP.get()!!.loginInfo != null) {
            loginBean = APP.get()!!.loginInfo
            goPaymentPresenter!!.getUserInfo(loginBean!!.userId!!)
            goPaymentPresenter!!.getAvailableCouponList(orderId!!)
            goPaymentPresenter.getWindowList(loginBean!!.userId!!)
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        goPaymentPresenter.detachView()
    }
}